const express = require('express');
const Router = express.Router();
const mongoose = require('mongoose');
const model = require('../models/Schema');
const Test = model.getModel('test');
var types = require('./dbTypes');
var Logger = require('../server/logger');
const logger = Logger.GetLogger('api/form')
logger.info('api/form 加载成功...')

Router.get('/list', (req, res) => {
  Test.find({}, (err, doc) => {
    if(err) throw err;
    res.json({code:types.SUCCESS_CODE,data:doc,message: types.SUCCESS_MESSAGE_FIND})
  })
})

Router.post('/add/test',(req, res) => {
  Test.create(req.body, (err, doc) => {
    if(err) throw err;
    res.json({code:types.SUCCESS_CODE,data:doc,message: types.SUCCESS_MESSAGE_SAVE})
  })
})

Router.post('/update/test', async (req, res) => {
  let {_id,page,pageSize} = req.body;
  let sid = mongoose.Types.ObjectId(_id);
  let retPage = void 0;
  let count = null;
  Test.count({}, (err,doc) => {
    count = doc;
  })
  let doc = await Test.findByIdAndUpdate({'_id': sid},{$set:req.body},{new: true}).exec()
  if(doc) {
    retPage = await Test.find({}).skip((page-1) * pageSize).limit(Number(pageSize)).sort({'_id':-1}).exec()
  }
  if(retPage && doc) {
    const data = {count: count, data:retPage}
    res.json({code: types.SUCCESS_CODE,data,update:doc,message: types.SUCCESS_MESSAGE_UPDATE})
  }
})

Router.post(`/delect/test`, async (req, res) => {
  let {key,page,pageSize} = req.body;
  let sid = mongoose.Types.ObjectId(key);
  let retPage = void 0;
  let count = null;
  Test.count({}, (err,doc) => {
    count = doc;
  })
  let doc = await Test.remove({'_id':sid}).exec()
  if(doc) {
    retPage = await Test.find({}).skip((page-1) * pageSize).limit(Number(pageSize)).sort({'_id':-1}).exec()
  }
  if(retPage && doc) {
    const data = {count: count, data:retPage}
    res.json({code: types.SUCCESS_CODE,data,delect:doc,message: types.SUCCESS_MESSAGE_DELECT})
  }
})

Router.post('/search/test', (req, res) => {
  let {id, page, pageSize,queryObj} = req.body;
  let count = null;
    Test.count(queryObj, (err,doc) => {
      count = doc;
    })
    if (!id) {
      Test.find(queryObj).skip((page-1) * pageSize).limit(Number(pageSize)).sort({'_id':-1}).exec((err, doc) => {
        if(err) throw err;
        const data = {count, data:doc}
        res.json({code:types.SUCCESS_CODE,data,message: types.SUCCESS_MESSAGE_FIND})
    })
  }else {
    let sid = mongoose.Types.ObjectId(id);
    Test.find({'_id':{"$lt":sid}}).limit(Number(pageSize)).sort({'_id':-1}).exec((err, doc) => {
      if(err) throw err;
      const data = {count, data:doc}
      res.json({code:types.SUCCESS_CODE,data,message: types.SUCCESS_MESSAGE_FIND})
    })
  }
})

module.exports = Router